package com.thiswhyme.gateway.sentinel.service;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.thiswhyme.gateway.sentinel.config.NacosRouteProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * @description: 监听nacos路由配置文件的更新服务
 * @author: thiswhyme
 * @date: 2020/8/27
 */
@Slf4j
@Service
public class DynamicRouteServiceByNacos implements CommandLineRunner {

    @Autowired
    private NacosRouteProperties nacosGatewayProperties;

    @Autowired
    private DynamicRouteService dynamicRouteService;

    /**
     * 监听nacos上路由配置文件的更新事件
     */
    public void dynamicRouteByNacosListener() {
        try {
            Properties properties = new Properties();
            properties.put("serverAddr", nacosGatewayProperties.getAddress());
            properties.put("namespace", nacosGatewayProperties.getNamespace());
            ConfigService config = NacosFactory.createConfigService(properties);
            String content = config.getConfig(nacosGatewayProperties.getDataId(), nacosGatewayProperties.getGroupId(), nacosGatewayProperties.getTimeout());
            dynamicRouteService.refreshRoutes(content);

            config.addListener(nacosGatewayProperties.getDataId(), nacosGatewayProperties.getGroupId(), new Listener() {
                @Override
                public void receiveConfigInfo(String config) {
                    dynamicRouteService.refreshRoutes(config);
                }

                @Override
                public Executor getExecutor() {
                    return null;
                }
            });
        } catch (Exception e) {
            log.error("register dynamic route listener error", e);
        }
    }

    @Override
    public void run(String... args) {
        dynamicRouteByNacosListener();
    }
}
